package org.example.day04;

/**
 * 第二章节2.2.2:synchronized同步代码块的使用
 * -仍然是串行执行
 */
public class MyThread2 {
    public void serviceMethod() {
        synchronized (this) {
            try {
                System.out.println("beginTime = " + System.currentTimeMillis());
                Thread.sleep(2000);
                System.out.println("endTime = " + System.currentTimeMillis());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        MyThread2 m2 = new MyThread2();
        Thread2A ta = new Thread2A(m2);
        ta.setName("A");
        ta.start();
        Thread2B tb = new Thread2B(m2);
        tb.setName("B");
        tb.start();
    }
}

class Thread2A extends Thread {
    private MyThread2 m2;
    public Thread2A(MyThread2 m2) {
        this.m2 = m2;
    }
    @Override
    public void run() {
        m2.serviceMethod();
    }
}

class Thread2B extends Thread{
    private MyThread2 m2;
    public Thread2B(MyThread2 m2) {
        this.m2 = m2;
    }
    @Override
    public void run() {
        m2.serviceMethod();
    }
}